<template>
  <div id="cart-page">
    <div style="width: 100%; position: fixed; top: 0px; background: #FFFFFF; z-index: 5" :style="{
      height:this.getSafeArea().top+'px'
    }" ></div>
    <div class="page-title" style="background: #FFFFFF" :style="{top:(this.getSafeArea().top-4)+'px'}">
      <div id="back-button" @click="goBack()">
        <i href="javascript:void(0)" class="el-icon-arrow-left"></i>
      </div>
      <span>购物车</span>
      <el-button type="danger" class="slected-buynow-button" @click="gotoBuy"
                 v-if="selectedNums>0">结算
      </el-button>
    </div>
    <div style="position: relative; overflow-x: hidden; overflow-y: auto; background: #f1f1f1; padding-bottom: 65px;" :style="{
      top:(this.getSafeArea().top+35)+'px',
    height:(getWinSize().height-86-this.getSafeArea().top)+'px'
  }">
      <div class="one-shop-box" v-for="(shopItem,index) in allList">
        <div class="shop-box">
          <div class="check-box">
            <el-checkbox v-model="shopItem.shop.select" @change="checkShopSelect($event,shopItem.shop)"
                         :value="shopItem.id"></el-checkbox>
          </div>
          <div class="shop-logo" @click="$router.push('ShopHome?id='+shopItem.shop.id)">
            <img :src="shopItem.shop.logo">
          </div>
          <div class="shop-name" v-text="shopItem.shop.name"
               @click="$router.push('ShopHome?id='+shopItem.shop.id)"></div>
          <i class="el-icon el-icon-delete-solid" @click="delShop(index)"></i>
          <div class="c"></div>
        </div>
        <div class="product-list">
          <div class="item" v-for="(product,_index) in shopItem.productList" :key="_index">
            <div class="left">
              <el-checkbox :disabled="product.status===0" v-model="productSelectMap[product.id]"
                           @change="changeSelectNums(shopItem.shop.id)"></el-checkbox>
            </div>
            <div class="right">
              <div class="right-product-image" :style="{
                height:Math.ceil(getWinSize().width*0.3)+'px'
              }">
                <div class="is-disabled" v-show="product.status===0">已下架</div>
                <img :src="product.image?product.image:product.shopProductImage" alt="" @click="toProductDetail(product)" style="max-width: 80px; max-height: 80px;">
              </div>
              <div class="right-product-other">
                <div class="product-name">
                  <span v-text="product.shopProductName" @click="toProductDetail(product)"></span>
                </div>
                <div class="product-model">
                  <span v-text="getNewPriceModel(product,'model')" @click="chooseModel(product)"></span>
                  <i class="el-icon-arrow-down" v-if="product.model.indexOf(',')>0"></i>
                </div>
                <div class="product-price">
                  <div class="price red" v-text="'￥'+ToMoney(getNewPriceModel(product,'price'))"></div>
                  <div class="nums demo">
                    <el-input-number controls-position="right" :max="1000" :min="1" v-model="product.nums"
                                     @change="changeProductNums(product)"></el-input-number>
                  </div>
                </div>
                <div class="product-del-button" @click="delItem(product)">
                  <i class="el-icon el-icon-delete-solid"></i>
                </div>
              </div>
              <div class="c"></div>
            </div>
            <div class="c"></div>
          </div>
          <div class="c"></div>
        </div>
      </div>
    </div>

    <!--空数据-->
    <div v-if="allList.length===0"
         style="height: 45px; width: 100%; line-height: 45px; color: #888888; font-size: 16px; text-align: center; top: 150px; position: fixed;">
      <i class="icon-cebianlandanchu"></i>
      未选择商品....
    </div>

  </div>
</template>

<script>
import CartTools from '../tools/CartTools'

export default {
  name: 'Cart',
  data: function () {
    return {
      selectData:{},
      isShifu: this.CurrUser.isShifu,
      allList: [],
      productSelectMap: {},
      productNewModelMap: {},
      selectedNums: 0,
      shopSelectArr: [],
    }
  },
  mounted () {
    let $this=this
    $this.getCartItemList(function () {
      $this.handleList()
    })
    // localStorage.setItem("CartCache",'[{"shop":{"id":1,"logo":"http://image.yangfankj.com/shop/logo/1.jpg","name":"华盛五金店"},"productList":[{"id":2,"image":"http://image.yangfankj.com/product/104/0.jpg","name":"德力西-冲击钻","price":265,"model":"常规","nums":1},{"id":1,"image":"http://image.yangfankj.com/product/110/0.jpg","name":"威马-电动螺丝刀","price":122.05,"model":"大,黑","nums":1},{"id":3,"image":"http://image.yangfankj.com/product/103/0.jpg","name":"德国欧莱德-磨角机","price":215,"model":"常规","nums":1}]},{"shop":{"id":2,"logo":"http://image.yangfankj.com/shop/logo/2.jpg","name":"飞扬五金"},"productList":[{"id":5,"image":"http://image.yangfankj.com/product/105/0.jpg","name":"东成-气动直钉枪","price":195,"model":"常规","nums":1},{"id":6,"image":"http://image.yangfankj.com/product/104/0.jpg","name":"德力西-冲击钻","price":275,"model":"常规","nums":1}]},{"shop":{"id":3,"logo":"http://image.yangfankj.com/shop/logo/3.jpg","name":"国红五金水暖店"},"productList":[{"id":11,"image":"http://image.yangfankj.com/product/105/0.jpg","name":"东成-气动直钉枪","price":195,"model":"常规","nums":1}]},{"shop":{"id":4,"logo":"http://image.yangfankj.com/shop/logo/4.jpg","name":"阳蕙五金店"},"productList":[{"id":12,"image":"http://image.yangfankj.com/product/110/0.jpg","name":"威马-电动螺丝刀","price":135,"model":"常规","nums":1}]},{"shop":{"id":7,"logo":"http://image.yangfankj.com/shop/logo/7.jpg","name":"唐久便利"},"productList":[{"id":20,"image":"http://image.yangfankj.com/product/7/0/0.png","name":"百事可乐","price":5,"model":"常规","nums":1}]},{"shop":{"id":6,"logo":"http://image.yangfankj.com/shop/logo/6.jpg","name":"金三角五金水暖经销部"},"productList":[{"id":19,"image":"http://image.yangfankj.com/product/105/0.jpg","name":"东成-气动直钉枪","price":195,"model":"常规","nums":1}]},{"shop":{"id":8,"logo":"http://image.yangfankj.com/shop/logo/8.jpg","name":"人人乐"},"productList":[{"id":25,"image":"http://image.yangfankj.com/product/7/0/0.png","name":"百事可乐","price":5,"model":"常规","nums":1},{"id":26,"image":"http://image.yangfankj.com/product/8/9/0.png","name":"山西汾酒","price":86,"model":"常规","nums":1},{"id":27,"image":"http://image.yangfankj.com/product/8/5/0.png","name":"欧莱雅 紫熨斗眼霜","price":145,"model":"常规","nums":1}]}]')
  },
  methods: {
    toProductDetail:function (product) {
      this.$router.push({
        name:'ProductDetail',
        query:{
          id:product.shopProductId,
          model:product.model,
        }
      })
    },
    goBack: function () {
      if (this.$route.query.fromUrl) {
        this.$router.push(decodeURI(this.$route.query.fromUrl))
      } else {
        this.$router.back()
      }
    },
    getNewPriceModel: function (productItem, key) {
      var map = this.productNewModelMap[productItem.id]
      if (map) {
        return map[key]
      } else {
        return productItem[key]
      }
    },
    chooseModel: function (productParams) {
      if (productParams.model.indexOf(',') === -1) {
        return
      }
      productParams.currModel = this.getNewPriceModel(productParams, 'model')
      let $this = this
      $this.bus.$emit('ProductChooseModelDialogCallBus', 'cartPage', productParams, function (modelData) {
        $this.allList.forEach(function (item, index) {
          $this.allList[index].shop.select = false
          item.productList.forEach(function (_value, _index) {
            if (_value.id === productParams.id) {
              _value.model = modelData.model
              _value.price = modelData.price
              $this.$set($this.productNewModelMap, productParams.id, {
                model: modelData.model,
                price: modelData.price,
              })
            }
          })
        })

        // 同步缓存
        CartTools.setAllList($this.allList)
        $this.$forceUpdate()
      })
    },
    // 准备结算
    gotoBuy: function () {
      if (this.shopSelectArr.length>1){
        // return this.$message.warning('每次只能提交一个店铺商品')
      }
      if (this.getIsShifu()) {
        // 有师傅
        let $this = this
        var type = this.getSelectData()
        if (type==='one'){
          $this.MyRequest($this.ApiDoNameMember + 'Member/isBindingShop', {shopId: $this.selectData.shop.id}, function (isBinding) {
            $this.bus.$emit('CartSubmitDialogCallBus', isBinding, function (submitType) {
              if (submitType === 0) {
                $this.submitOrder()
              }
              if (submitType === 1) {
                $this.submitShopProductPurchaseOrder()
              }
            })
          }, function (msg) {
            $this.$message.error(msg)
          })
        }else{
          this.submitOrder()
        }
      } else {
        // 没有师傅绑定
        this.submitOrder()
      }
    },
    getSelectData: function () {
      let $this = this
      var selectDataList = []
      $this.allList.forEach(function (item, index) {
        var selectData = {}
        if (item.shop.select) {
          var productList = []
          item.productList.forEach(function (value, index) {
            if ($this.productSelectMap[value.id] === true) {
              console.log('value',value)
              value.name=value.shopProductName
              productList.push(value)
            }
          })
          if (productList.length > 0) {
            selectData = Object.assign({}, item)
            selectData.productList = productList
          }
          selectDataList.push(selectData)
        }
      })
      if (selectDataList.length>0 && selectDataList.length===1){
        $this.selectData=selectDataList[0]
        localStorage.setItem('selectProductData', JSON.stringify(selectDataList[0]))
        return 'one'
      }
      if (selectDataList.length>0 && selectDataList.length>1){
        localStorage.setItem('selectProductDataList', JSON.stringify(selectDataList))
        return 'more'
      }
      return 'empty'
    },
    // 提交-采购单
    submitShopProductPurchaseOrder: function () {
      var type=this.getSelectData()
      if (type==='empty'){
        return this.$message.error('请先选择商品数据')
      }
      this.$router.push('/ConfirmPurchaseOrder')
    },
    // 提交-订单
    submitOrder: function () {
      var type = this.getSelectData();
      if (type==='empty'){
        return this.$message.error('请先选择商品数据')
      }
      if (type==='one'){
        this.$router.push('/ConfirmOrder')
      }
      if (type==='more'){
        this.$router.push('/ConfirmOrderMore')
      }
    },
    changeProductNums: function (productParams) {
      if (!productParams.nums){
        productParams.nums=1
      }
      let $this=this
      $this.bus.$emit('CartUtilCallBus','setCartProductItem',{
        id:productParams.id,
        nums:productParams.nums,
      },function () {

      })
    },
    // 更改商品-数量
    changeSelectNums: function (product) {
      let $this = this
      var keysArr = Object.keys($this.productSelectMap)
      var i = 0
      keysArr.forEach(function (key, index) {
        if ($this.productSelectMap[key]) {
          i++
        }
      })
      $this.shopSelectArr = []
      var shopIndex = -1
      $this.allList.forEach(function (item, index) {
        var shopSelectNums=0
        item.productList.forEach(function (_value, _index) {
          if ($this.productSelectMap[_value.id] === true) {
            shopIndex = index
            if ($this.shopSelectArr.indexOf(item.shop.id) === -1) {
              $this.shopSelectArr.push(item.shop.id)
            }
            shopSelectNums+=_value.nums
          }
        })
        if (shopSelectNums===0){
          $this.$set($this.allList[index].shop, 'select', false)
        }
      })
      $this.selectedNums = i
      // console.log('$this.allList',$this.allList)
      if (shopIndex > -1) {
        $this.$set($this.allList[shopIndex].shop, 'select', true)
      }
      // $this.bus.$emit('CartUtilCallBus','setCartProductItem',{
      //   id:product.id,
      //   nums:0,
      // },function () {
      //
      // })
      $this.$forceUpdate()
    },
    // 删除-单个店铺-所有商品
    delShop: function (shopIndex) {
      let $this=this
      $this.bus.$emit('CartUtilCallBus','deleteCartShopItem',{
        shopId:$this.allList[shopIndex].shop.id,
      },function () {
        $this.allList.splice(shopIndex,1)
      })
    },
    // 删除-单个商品型号
    delItem: function (product) {
      let $this=this
      $this.bus.$emit('CartUtilCallBus','deleteCartProductStockItem',{
        id:product.id,
        nums:0,
      },function () {
        var index0=-1
        var index1=-1
        $this.allList.forEach(function (item, index) {
          $this.allList[index].shop.select = false
          item.productList.forEach(function (_value, _index) {
            if (_value.id===product.id){
              index0=index
              index1=_index
            }
          })
        })

        // 删除商品
        if (index0>-1 && index1>-1){
          $this.allList[index0].productList.splice(index1,1)
          // 如果当前店铺没有商品,就删除店铺
          if ($this.allList[index0].productList.length===0){
            $this.allList.splice(index0,1)
          }
        }
        $this.$forceUpdate()
      })
    },
    handleList: function () {
      let $this = this
      $this.allList.forEach(function (item, index) {
        $this.allList[index].shop.select = false
        item.productList.forEach(function (_value, _index) {
          $this.allList[index].productList[_index].select = false
          $this.$set($this.productSelectMap, _value.id, false)
        })
      })
      $this.selectedNums = 0
      $this.$forceUpdate()
    },
    checkShopSelect: function (e, shopItem) {
      let $this = this
      $this.allList.forEach(function (item, index) {
        if (item.shop.id === shopItem.id) {
          item.productList.forEach(function (_value, _index) {
            $this.allList[index].productList[_index].select = shopItem.select
            $this.$set($this.productSelectMap, _value.id, shopItem.select)
          })
        }
      })
      $this.changeSelectNums(shopItem.id)
      $this.$forceUpdate()
    },
    setItemRequest:function (type,shopProductStockId,nums,model,callback) {
      model=model?model:''
      let $this=this
      var api='Member/setCartItem'
      $this.MyRequest($this.ApiDoNameMember+api,{type,shopProductStockId,nums,model},function () {
        if (typeof callback==='function'){
          callback()
        }
      },function () {
        callback()
      })
    },
    getCartItemList:function (callback) {
      let $this=this
      var api = 'Member/getCartItemList'
      $this.MyRequest($this.ApiDoNameMember+api,{},function (allList) {
        // $this.allList=allList
        $this.allList=allList
        callback()
      },function () {

      })
    }
  }
}
</script>

<style scoped>

</style>
